const {jwt:jwtConf} = require('../config')
// 安装并导入 JWT 相关的两个包，分别是 jsonwebtoken 和 express-jwt
const jwt = require('jsonwebtoken');

const analyzeToken = (req, res, next) => {
    let reg = new RegExp(/^\/api\//,'g')
    if (reg.test(req.url)){
        next()
        return
    }
    if (req.headers.authorization){
        let tokenStr = req.headers.authorization.replace('Bearer ','')
        jwt.verify(tokenStr, jwtConf.jwtSecretKey, (err, decoded) =>{
            if (err) {
                throw new Error('jwt的错误：'+err.message)
            }
            req.user = decoded
            // console.log(req.user)
            next()
        })
        return
    }
    throw new Error(`Invalid authorization header`)

}

const sendJson = (req, res, next) => {
    // status 默认值为 1，表示失败的情况
    // err 的值，可能是一个错误对象，也可能是一个错误的描述字符串
    res.sendJson = (err, status = 1, data = null) => {
        let result = {
            status,
            message: err instanceof Error ? err.message : err
        }
        if (data) {
            result['data'] = data
        }
        res.send(result)
    }
    next()
}

module.exports = {
    sendJson,
    analyzeToken
}